package com.orange.monitor.fileListener;

import java.io.File;
import java.util.Map;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.log4j.Logger;

import com.orange.expireFile.entity.ExpireFile;
import com.orange.expireFile.format.ExpireFileFormat;
import com.orange.quartz.context.QuartzJobContext;

/**
 * @author: HH
 * @Description: 具体监听类，细化到每一个文件、目录的变化 
 * @date 2017年9月18日 下午6:38:22
 */
public class FileListener implements FileAlterationListener {

	private static final Logger logger = Logger.getLogger(FileListener.class);

	/**
	 * 目录更改
	 */
	public void onDirectoryChange(File arg0) {
		logger.info("director changed : " + arg0.getAbsolutePath());
	}

	/**
	 * 目录创建
	 */
	public void onDirectoryCreate(File arg0) {
		logger.info("director created : " + arg0.getAbsolutePath());
	}

	/**
	 * 目录删除
	 */
	public void onDirectoryDelete(File arg0) {
		logger.info("director deleted : " + arg0.getAbsolutePath());
	}

	/**
	 * 文件变化
	 */
	public void onFileChange(File arg0) {
		String filePath = arg0.getAbsolutePath();
		logger.info("file changed : " + filePath);
		if(filePath.contains("expireFileInfos") && filePath.endsWith(".xml")){
			try {
				//重新加载过期配置文件
				Map<String, ExpireFile> expireFileMap = ExpireFileFormat.getExpireFileMapByXml(filePath);
				//重新初始化调度
				QuartzJobContext.initScheduleJobMap(expireFileMap);
				QuartzJobContext.setAllJobs();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 文件创建
	 */
	public void onFileCreate(File arg0) {
		logger.info("file created : " + arg0.getAbsolutePath());
	}

	/**
	 * 文件删除
	 */
	public void onFileDelete(File arg0) {
		logger.info("file deleted : " + arg0.getAbsolutePath());
	}

	/**
	 * 开始扫描
	 */
	public void onStart(FileAlterationObserver arg0) {
		logger.info("monitor start scanning..");
	}

	/**
	 * 结束扫描
	 */
	public void onStop(FileAlterationObserver arg0) {
		logger.info("monitor stop scanning..");
	}

}
